/*
 * @Author: lyuan2018
 * @Date: 2019-08-08 10:54:30
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 15:52:18
 * 邮件设置--账户管理--主页
 */
import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Radio, Switch, Modal } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon } from 'ecCom';
import { AntdConfirm } from '../util';
import New from './New';
import Edit from './Edit';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

@inject('settingStore', 'emailMenuStore')
@observer
class Account extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-account',
  };

  constructor(props) {
    super(props);
    this.state = {
      accountNewVisible: false,
    };
  }

  componentWillMount() {
    const {
      settingStore: { accountStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: () => accountStore.getMailAccount(),
      },
    ];
    setStoreState({ rightMenuDatas });
    accountStore.getMailAccount();
    accountStore.setStoreState({ accoutOpt: this.menuOpt });
  }

  menuOpt = () => {
    const { emailMenuStore } = this.props;
    emailMenuStore && emailMenuStore.getMenu();
  };

  // 默认
  radioChange = (e, record) => {
    const {
      settingStore: { accountStore },
    } = this.props;
    let defaultID = record.randomFieldId;
    accountStore.updateUserDefaultMailAccount({ defaultID });
  };

  // 默认
  switchChange = (e, record) => {
    if (e) {
      Modal.confirm({
        title: getLabel(510826, '温馨提示'),
        content: (
          <div className="wea-list-confirm">
            <p style={{ 'font-weight': '700' }}>
              {getLabel(515692, '亲爱的用户，欢迎使用发票识别功能。')}
            </p>
            <p>
              {getLabel(
                515695,
                '1.为保证发票识别功能正常使用，我们会根据需要收集个人邮箱中公司指定发件人发送的发票信息，获取之后也仅作为用户及其公司在OA系统中的相关财务业务往来',
              )}
            </p>
            <p>
              {getLabel(
                515696,
                '2.我们非常重视您的隐私和个人信息保护，未经授权，不会私自收集、使用、共享您邮件中的个人信息，请放心使用',
              )}
            </p>
          </div>
        ),
        okText: getLabel(826, '确定'),
        cancelText: getLabel(31129, '取消'),
        onOk: () => {
          const {
            settingStore: { accountStore },
          } = this.props;
          let id = record.randomFieldId;
          accountStore.openIdentifyInvoiceMailAccount({
            openIdentifyInvoice: e ? 1 : 0,
            id,
          });
        },
      });
    } else {
      const {
        settingStore: { accountStore },
      } = this.props;
      let id = record.randomFieldId;
      accountStore.openIdentifyInvoiceMailAccount({
        openIdentifyInvoice: e ? 1 : 0,
        id,
      });
    }
  };

  onOperatesClick = (record, index, operate) => {
    if (operate.index === '0') {
      // edit
      this.editAccount(record);
    } else if (operate.index === '1') {
      this.batchDel(record.randomFieldId);
    }
  };

  // 删除
  batchDel = (id) => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { accountTable, deleteUserMailAccount } = accountStore;
    let mailAccountIDs =
      id || toJS(accountTable.selectedRowKeysAllPages).join();
    AntdConfirm(
      { content: getLabel(81509, '删除邮件账户会删除账户下的邮件，确认删除?') },
      () => {
        deleteUserMailAccount({ mailAccountIDs });
      },
    );
  };

  // 编辑
  editAccount = (record) => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const {
      getEmailAccountCondition,
      getMailAccountBean,
      setStoreState,
    } = accountStore;
    let id = record.randomFieldId;
    getEmailAccountCondition({ id }, () => {
      getMailAccountBean({ id }, () => {
        setStoreState({ editVisible: true, editId: id });
      });
    });
  };

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === 'isDefault') {
          return (
            <Radio
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Radio@nsq6b4@${text}`}
              type="checkbox"
              checked={record.isDefault * 1 === 1}
              onChange={e => this.radioChange(e, record)}
            />
          );
        } else if (newColumn.dataIndex == 'openIdentifyInvoice') {
          return (
            <Switch
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Switch@fb78vo@${record.randomFieldId}`}
              size="small"
              checked={record.openIdentifyInvoice * 1 === 1}
              defaultChecked={false}
              onChange={e => this.switchChange(e, record)}
            />
          );
        } else if (newColumn.dataIndex == 'accountName') {
          return (
            <div
              onClick={() => this.editAccount(record)}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };

  onAddClick = () => {
    this.refs.newAccount.wrappedInstance.addAccount(() =>
      this.setState({ accountNewVisible: true }),
    );
  };

  onNewAccountCancel = () => this.setState({ accountNewVisible: false });

  render() {
    const {
      prefixCls,
      settingStore: { accountStore },
    } = this.props;
    const { accountTable, getMailAccount } = accountStore;
    const tabButtons = [
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@ix11j8@add`}
        buttonType="add"
        type="primary"
        onClick={this.onAddClick}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@5qhe7k@del`}
        buttonType="del"
        type="primary"
        disabled={toJS(accountTable.selectedRowKeysAllPages).length === 0}
        onClick={() => this.batchDel()}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@alhlgk`}
          datas={[{ title: getLabel(384438, '账户列表'), viewcondition: '0' }]}
          keyParam="viewcondition"
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@pvbg0u`}
          comsWeaTableStore={accountTable}
          hasOrder
          needScroll
          onOperatesClick={this.onOperatesClick}
          getColumns={this.getColumns}
        />
        <div className={`${prefixCls}-tip`}>
          <p className="wea-f14">{getLabel(558, '提示')}：</p>
          <p className="wea-f12">
            {getLabel(384441, '*OA服务器能够访问到邮箱服务器25,110端口')}
          </p>
          <p className="wea-f12">
            {getLabel(
              384442,
              '*如检查163邮箱服务器是否通畅，在OA服务器上：telnet smtp.163.com 25',
            )}
          </p>
        </div>
        <New
          ecId={`${(this && this.props && this.props.ecId) || ''}_New@agr19w`}
          ref="newAccount"
          visible={this.state.accountNewVisible}
          onCancel={this.onNewAccountCancel}
          onSubmit={getMailAccount}
        />
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@fy3hea`}
          class={prefixCls}
        />
      </div>
    );
  }
}

export default Account;
